var createError = require('http-errors');
var express = require('express');// h[10]
var FileStreamRotator = require('file-stream-rotator');//日志文件分割
var path = require('path');
var cookieParser = require('cookie-parser');
var morgan = require('morgan');
var morganComfig = require('./utils/morgan-config');//morgan日志的配置
var fs = require('fs');//操作文件的依赖
var bodyParser = require('body-parser');// 处理json 等数据格式的中间件
var hcsy = require('./utils/hcsy-date');//引用自己的文件

var loggerInfo = require('./utils/winston-date').logger;// 自定义打印 包含日志文件分割功能
var loggerError = require('./utils/winston-date').loggerError;// 自定义打印 包含日志文件分割功能
var session = require('express-session');//seesion 会话
//自定义路由
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/nosign');
var pcRouter = require('./routes/pc');
var jdRouter = require('./routes/JD');
var snRouter = require('./routes/SN');
var jhRouter = require('./routes/jh');
// var product=require("./routes/product");//这行有错误
// // create application/json parser
// var jsonParser = bodyParser.json()
// // create application/x-www-form-urlencoded parser
// var urlencodedParser = bodyParser.urlencoded({ extended: false })

/*----------------------------------------------------------------------- */
var app = express();// h[2] 创建express实例

/*--------------------------------日志模块--------------------------------------- */
//只会打印 4xxx 和 5xxx 的请求
app.use(morgan('error', {
  skip: function (req, res) { return res.statusCode < 400 },
  stream: morganComfig.accessLogStream
}))
app.use(morgan('info', {
  skip: function (req, res) { },
  stream: morganComfig.accessLogStreamInfo
}))

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  //这段仅仅为了方便返回json而已
  res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method == 'OPTIONS') {
    //让options请求快速返回
    res.sendStatus(200);
  } else {
    next();
  }
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(morgan('dev'));
app.use(express.json({ limit: '5mb' }));  // 通过js向后台post一些文件信息时,会报错误。这是express框架的问题,默认的很小,可以通过设置:app.use(express.json({limit: '5mb'}));
app.use(express.urlencoded({ extended: false }));//处理JSON 数据
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

/**
 * 会话管理
 */
var identityKey = 'skey';
app.use(session({
  // name: identityKey,
  secret: 'chyingp',  // 用来对session id相关的cookie进行签名
  // store: new FileStore(),  // 本地存储session（文本文件，也可以选择其他store，比如redis的）
  saveUninitialized: false,  // 是否自动保存未初始化的会话，建议false
  resave: false,  // 是否每次都重新保存会话，建议false
  cookie: {
    maxAge: 1 * 60 * 100 * 1000  // 有效期，单位是毫秒
  }
}));

// 过滤器
app.use(function (req, res, next) {
  console.log("过滤器", req.body);
  /**
   * 在/api/login下的接口不需要登录
   */
  var reqBody = "";
  if (req.method == 'GET') {
    reqBody = req.query;
  } else {
    reqBody = req.body;
  }
  //配置不需要登录的接口
  var nosignArr = ['api/nosign', 'api/pc', 'api/JD','api/SN','api/jh'];
  var resUrl = req.url;
  resUrl = resUrl.split("/");
  resUrl = resUrl[1] + "/" + resUrl[2];
  //if (req.url.indexOf("api/nosign") == -1) {
  if (nosignArr.indexOf(resUrl) == -1) {
    if (req.session.token && req.session.token == reqBody.token) {
      console.log("登录成功");
      req.session.token = null;
    } else {
      console.log("过滤器");
      loggerInfo.info("未登录", req.url, req.ip);
      res.json({ code: 500, data: "", msg: "未登录" });
      return;
      //return res.redirect('www.baidu.com');
    }
  }
  next();
  //next(createError(404));
});

/**
 * 具体操作路径 一定要写在 app.use(function (req, res, next) { 之后
 */
app.use('/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/nosign', loginRouter);
app.use('/api/pc', pcRouter);
app.use('/api/JD', jdRouter);
app.use('/api/SN', snRouter);
app.use('/api/jh',jhRouter);

// // error handler
// app.use(function (err, req, res, next) {
//   console.log("中心登录成功");
//   // console.log("-------------------------------------------------中奖执行----------------------------------");
//   // console.log(">>>>", err);
//   // console.log(req);
//   // console.log(res);
//   // console.log(next);
//   // set locals, only providing error in development
//   // 设置在本地开发中, 只提供开发中的错误
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};

//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });

module.exports = app;
